from requests.api import post
from config_data import API_KEY, ROBOOT_API, ROOM_NAME, USER_DATA
import json
import requests
import sys
import inspect

base_url = "https://www.yuque.com/"
MAP={}

def analyze_route(post_data):
    post_data = json.loads(post_data)
    text = None
    
    try:
        text = MAP.get(post_data['data']['action_type'])(post_data['data'])
    except KeyError  :
        print("未注册路由："+post_data['data']['action_type'])
    # 如果消息不为空就发送
    if text :
        send_room_message(text)

def router(route):
    def _(func):
        def process_wrap(post_data):
            return func(post_data)
        MAP[route]=process_wrap
        return process_wrap
    return _


@router("publish")
def process_publish(post_data):
    """文档知识库：处理新文档发布消息"""
    user_info = USER_DATA.get(post_data['user_id'])
    url = base_url + post_data['path']
    text = f"新文档:\n{user_info['name']} 发布了\n《{post_data['title']}》\n欢迎大家访问\n{url}"
    return text


@router("update")
def process_update(post_data):
    """文档知识库：处理新文档更新消息"""
    user_info = USER_DATA.get(post_data['user_id'])
    actor_info = USER_DATA.get(post_data['actor_id'])
    url = base_url + post_data['path']
    if post_data['user_id'] == post_data['actor_id']:
        text = f"文档更新:\n{user_info['name']} 更新了自己的\n《{post_data['title']}》\n欢迎大家访问\n{url}"
    else:
        text = f"文档更新:\n{actor_info['name']}更新了{user_info['name']}的\n《{post_data['title']}》\n快来看看吧\n{url}"

    return text

@router("comment_create")
def process_comment(post_data):
    """文档知识库：处理新增评论消息"""
    user_info = USER_DATA.get(post_data['commentable']['user_id'])
    actor_name = post_data['user']['name']
    url = base_url + post_data['commentable']['path']
    text = f"可爱的{actor_name}评论了{user_info['name']}的\n《{post_data['commentable']['title']}》\n快来看看吧\n{url}"
    return text



def send_room_message(text):
    url = ROBOOT_API
    data = {
        "apiKey" : API_KEY,
        "roomName": ROOM_NAME,
        "message": {
            "type": 1,
            "content": text
        }
    }
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=json.dumps(data))

    print(response.status_code)
    print(text)

# 下面这个是用来单元测试的
# if __name__ == "__main__":
#     postdata = None
#     with open("comment_data.json",encoding="utf8") as file:
#         analyze_route(file.read())
    # print(getattr(sys.modules[__name__],"process_publish"))

    # print(MAP)